"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { Progress } from "@/components/ui/progress"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { CheckCircle, XCircle } from "lucide-react"
import { readingQuestions } from "@/lib/questions-data"
import { useUser } from "@/lib/user-context"
import { useToast } from "@/components/ui/use-toast"

export default function ReadingPage() {
  const [currentPassageIndex, setCurrentPassageIndex] = useState(0)
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
  const [selectedOption, setSelectedOption] = useState<string | null>(null)
  const [isAnswered, setIsAnswered] = useState(false)
  const [isCorrect, setIsCorrect] = useState(false)
  const [score, setScore] = useState(0)
  const [wrongAnswers, setWrongAnswers] = useState<any[]>([])
  const router = useRouter()
  const { user } = useUser()
  const { toast } = useToast()

  const currentPassage = readingQuestions[currentPassageIndex]
  const currentQuestion = currentPassage.questions[currentQuestionIndex]
  const totalQuestions = readingQuestions.reduce((acc, passage) => acc + passage.questions.length, 0)
  const completedQuestions =
    readingQuestions.slice(0, currentPassageIndex).reduce((acc, passage) => acc + passage.questions.length, 0) +
    currentQuestionIndex
  const progress = ((completedQuestions + 1) / totalQuestions) * 100

  // 如果用户未登录，重定向到首页
  useEffect(() => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能进行练习",
        variant: "destructive",
      })
      router.push("/")
    }
  }, [user, router, toast])

  // 检查答案
  const checkAnswer = () => {
    if (!selectedOption) return

    const isAnswerCorrect = selectedOption === currentQuestion.correctAnswer
    setIsCorrect(isAnswerCorrect)
    setIsAnswered(true)

    if (isAnswerCorrect) {
      setScore(score + 1)
    } else {
      // 添加到错题本
      const wrongAnswer = {
        ...currentQuestion,
        passage: currentPassage.passage,
        userAnswer: selectedOption,
        type: "reading",
      }
      setWrongAnswers([...wrongAnswers, wrongAnswer])

      // 保存到本地存储
      const storedWrongAnswers = JSON.parse(localStorage.getItem("wrongAnswers") || "[]")
      localStorage.setItem("wrongAnswers", JSON.stringify([...storedWrongAnswers, wrongAnswer]))
    }
  }

  // 下一题
  const nextQuestion = () => {
    // 检查是否还有下一个问题在当前段落中
    if (currentQuestionIndex < currentPassage.questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1)
      setSelectedOption(null)
      setIsAnswered(false)
    }
    // 检查是否还有下一个段落
    else if (currentPassageIndex < readingQuestions.length - 1) {
      setCurrentPassageIndex(currentPassageIndex + 1)
      setCurrentQuestionIndex(0)
      setSelectedOption(null)
      setIsAnswered(false)
    }
    // 所有问题都已完成
    else {
      // 保存进度
      const progress = {
        reading: {
          completed: true,
          score: score,
          total: totalQuestions,
        },
      }

      const storedProgress = JSON.parse(localStorage.getItem("progress") || "{}")
      localStorage.setItem("progress", JSON.stringify({ ...storedProgress, ...progress }))

      // 显示完成信息
      toast({
        title: "练习完成！",
        description: `您的得分：${score}/${totalQuestions}`,
      })

      // 跳转到结果页面
      router.push("/practice/result?type=reading&score=" + score + "&total=" + totalQuestions)
    }
  }

  if (!user) {
    return null
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold mb-4">阅读理解练习</h1>
        <Progress value={progress} className="h-2" />
        <p className="text-sm text-muted-foreground mt-2">
          问题 {completedQuestions + 1} / {totalQuestions}
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card className="mb-6 md:mb-0">
          <CardHeader>
            <CardTitle>阅读文章 {currentPassageIndex + 1}</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="whitespace-pre-line">{currentPassage.passage}</p>
          </CardContent>
        </Card>

        <Card className="mb-6">
          <CardHeader>
            <CardTitle>问题 {currentQuestionIndex + 1}</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="mb-4">{currentQuestion.question}</p>

            <RadioGroup value={selectedOption || ""} onValueChange={setSelectedOption} className="space-y-3">
              {currentQuestion.options.map((option) => (
                <div
                  key={option.id}
                  className={`flex items-center space-x-2 rounded-md border p-3 ${
                    isAnswered && option.id === currentQuestion.correctAnswer
                      ? "border-green-500 bg-green-50 dark:bg-green-900/20"
                      : isAnswered && option.id === selectedOption
                        ? "border-red-500 bg-red-50 dark:bg-red-900/20"
                        : ""
                  }`}
                >
                  <RadioGroupItem value={option.id} id={`option-${option.id}`} disabled={isAnswered} />
                  <Label htmlFor={`option-${option.id}`} className="flex-1 cursor-pointer">
                    {option.id}. {option.text}
                  </Label>
                  {isAnswered && option.id === currentQuestion.correctAnswer && (
                    <CheckCircle className="h-5 w-5 text-green-500" />
                  )}
                  {isAnswered && option.id === selectedOption && option.id !== currentQuestion.correctAnswer && (
                    <XCircle className="h-5 w-5 text-red-500" />
                  )}
                </div>
              ))}
            </RadioGroup>

            {isAnswered && (
              <Alert className={`mt-4 ${isCorrect ? "border-green-500" : "border-red-500"}`}>
                <AlertTitle>{isCorrect ? "回答正确！" : "回答错误"}</AlertTitle>
                <AlertDescription>{currentQuestion.explanation}</AlertDescription>
              </Alert>
            )}
          </CardContent>
          <CardFooter className="flex justify-between">
            {!isAnswered ? (
              <Button onClick={checkAnswer} disabled={!selectedOption}>
                提交答案
              </Button>
            ) : (
              <Button onClick={nextQuestion}>
                {currentPassageIndex < readingQuestions.length - 1 ||
                currentQuestionIndex < currentPassage.questions.length - 1
                  ? "下一题"
                  : "完成"}
              </Button>
            )}
          </CardFooter>
        </Card>
      </div>
    </div>
  )
}
